//
//  PEOverviewVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/10.
//

#import "RHOverviewVC.h"
#import "RHPlantStatusCell.h"
#import "RHRunDataCell.h"
#import "RHPowerGenerationCell.h"
#import "RHDeviceStatusCell.h"
#import "RHEnergySaveCell.h"
#import "RHEnergyStatisticsCell.h"
#import "RHChargeDataCell.h"
#import "DevChartParamsModel.h"
#import "DevChartModel.h"
#import "SYChartTool.h"
#import "WSDatePickerView.h"
#import "RHChargeFullChartVC.h"
#import "DeviceChartFieldModel.h"
#import "RHNavigationController.h"
#import "CDZQRScanViewController.h"
#import "RHMeAssetContainVC.h"
#import "RHDeviceViewController.h"
#import "RHAlarmFaultOptionVC.h"
#import "RHHomePlantTopoCell.h"
#import "RHHomeToPoFullScreenVC.h"
#import "RHTopoModel.h"
#import "RHPlantInfoViewController.h"
#import "IFMMenu.h"
#import "RHOrganizationBindVC.h"
#import "RHFirmwareListVC.h"
#import "RHTools.h"

@interface RHOverviewVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *titleArr;

//电站状态
@property (nonatomic ,strong) NSDictionary *plantStatusDic;
//设备状态
@property (nonatomic ,strong) NSArray *deviceStatusArr;
//当日数据
@property (nonatomic ,strong) NSDictionary *runDic;
//能效排行
@property (nonatomic ,strong) NSArray *efficiencyRankArr;
//节能减排
@property (nonatomic ,strong) NSDictionary *emissionReductionDic;
//累计收益
@property (nonatomic ,strong) NSDictionary *cumulativeGainDic;
//充放电数据
@property (nonatomic ,strong) NSDictionary *chargeDic;

@property (nonatomic ,strong) NSArray *plantArr;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

@property (nonatomic ,strong) UIView *gradentView;

@property (nonatomic, strong) UIView *pointView;
@end

@implementation RHOverviewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"首页".rh_localized;
    [self createChartData];
    [self setupUI];
    [self getData];
    if ([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser) {
        [self getCanUpdateDevice];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    RHNavigationController *nav = (RHNavigationController*)self.navigationController;
    [nav setBackgoundClear:YES titleColor:UIColor.whiteColor];
   
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    RHNavigationController *nav = (RHNavigationController*)self.navigationController;
    [nav setBackgoundClear:NO titleColor:kCOLOR_HEX(@"333333")];
}

-(void)createChartData
{
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"ChargeAndDischarge"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];

}
-(void)getData
{
    [self getRunData];
//    [self getPlantList];
    [self getStationStatus];
//    [self getDeviceStatus];
    [self getEmissionReduction];
  
    [self getChargeAndDischargeWithChartModel:[self.chartParamsModel.chartList firstObject]];
    
}

-(void)setupUI
{
    //电站状态发生改变(编辑,转让,删除,修改图片,名称等)
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getData) name:PlantListNeedUpdateNotification object:nil];
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAssetList) name:PlantInfoDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getData) name:PlantTransferNotification object:nil];
    
    UIView *topView = kView;
    topView.layer.cornerRadius = 15;
    topView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    topView.layer.masksToBounds = YES;
    [topView setGradientBackgroundWithColors:@[kCOLOR_HEX(@"#6AD68A"),kCOLOR_HEX(@"#5FCCB4")] orientation:GradientOrientationLeftToRight];
   
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.height.offset(kNavHeight+70);
    }];
    
    //绑定上级用户  ,普通用户绑定上级或者绑定错了,重新绑定上级
    UIBarButtonItem *scanBtn = [UIBarButtonItem itemWithImage:@"user_bind_organization" ImageHighLight:@"user_bind_organization" Target:self Seletor:@selector(showMenu) CGRect:CGRectMake(0, 0, 30, 30)];
    
    
    //信息
    UIView *tipView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    QMUIButton *tipBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [tipBtn setImage:[UIImage imageNamed:@"kwt_home_message_white"] forState:UIControlStateNormal];
    [tipBtn setImage:[UIImage imageNamed:@"kwt_home_message_white"] forState:UIControlStateHighlighted];
    [tipBtn addTarget:self action:@selector(goToAlarmList) forControlEvents:UIControlEventTouchUpInside];
    [tipView addSubview:tipBtn];
    UIView *pointView = [[UIView alloc]initWithFrame:CGRectMake(20, 5, 5, 5)];
    pointView.backgroundColor = kCOLOR_HEX(@"F86666");
    pointView.layer.cornerRadius = 2.5;
    pointView.layer.masksToBounds = YES;
    [tipView addSubview:pointView];
    pointView.hidden = YES;
    self.pointView = pointView;
    
    UIBarButtonItem *tipItem = [[UIBarButtonItem alloc]initWithCustomView:tipView];
    if([PrivateMange share].currentUser.brandId == [brand_id longLongValue]){
        self.navigationItem.rightBarButtonItems = @[tipItem,scanBtn];
    }else{
        self.navigationItem.rightBarButtonItems = @[tipItem];
    }
   
    
    self.titleArr = @[@"",@"能量统计".rh_localized,@"社会贡献".rh_localized];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    
    [_tableView registerClass:[RHPlantStatusCell class] forCellReuseIdentifier:@"RHPlantStatusCell"];
    [_tableView registerClass:[RHRunDataCell class] forCellReuseIdentifier:@"RHRunDataCell"];
    [_tableView registerClass:[RHEnergyStatisticsCell class] forCellReuseIdentifier:@"PECumulativeGainCell"];
    
    [_tableView registerClass:[RHPowerGenerationCell class] forCellReuseIdentifier:@"RHPowerGenerationCell"];
    [_tableView registerClass:[RHDeviceStatusCell class] forCellReuseIdentifier:@"PEDeviceStatusCell"];
    [_tableView registerClass:[RHEnergySaveCell class] forCellReuseIdentifier:@"RHEnergySaveCell"];
    [_tableView registerClass:[RHChargeDataCell class] forCellReuseIdentifier:@"PEChargeDataCell"];
    [_tableView registerClass:[RHHomePlantTopoCell class] forCellReuseIdentifier:@"RHHomePlantTopoCell"];
    [self.view addSubview:_tableView];
    
    

    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 13.0, *)) {
        _tableView.automaticallyAdjustsScrollIndicatorInsets = NO;
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(kNavHeight, 0, 0, 0));
        }];
    }else{
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(kNavHeight, 0, 15, 0));
        }];
    }
    
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [self.tableView addHeaderRefresh:^{
        [weakSelf getData];
    }];
}

-(void)goToAlarmList
{
    RHAlarmFaultOptionVC *optionVC = [[RHAlarmFaultOptionVC alloc]init];
    [self.navigationController pushViewController:optionVC animated:YES];
}

-(void)showMenu
{
    /*
     ,
   [IFMMenuItem itemWithImage:[UIImage imageNamed:@"user_bind_scan"]
                        title:@"扫码绑定".rh_localized
                       action:^(IFMMenuItem *item) {
         [weakSelf scanQRC];
    }]
     */
     
    kWeakSelf;
   NSMutableArray *menuItems = [[NSMutableArray alloc] initWithObjects:
                  
      [IFMMenuItem itemWithImage:[UIImage imageNamed:@"user_bind_enter"]
                           title:@"手动绑定".rh_localized
                          action:^(IFMMenuItem *item) {
       [weakSelf bindToOrganization];
        }],nil];
    IFMMenu *menu = [[IFMMenu alloc] initWithItems:menuItems];
    menu.menuCornerRadiu = 8;
    menu.showShadow = YES;
    menu.minMenuItemHeight = 45;
    menu.titleColor = [UIColor colorWithHexString:@"3F4443" alpha:0.6];
    menu.titleFont = [UIFont systemFontOfSize:15];
    menu.menuBackgroundStyle = IFMMenuBackgroundStyleLight;
    
    [menu showFromNavigationController:self.navigationController WithX:[UIScreen mainScreen].bounds.size.width-70];
}

//绑定上级用户(旧)
//-(void)bindToSuper
//{
//    RHUserBindVC *bindVC = [[RHUserBindVC alloc]init];
//    [self.navigationController pushViewController:bindVC animated:YES];
//}

//绑定组织
-(void)bindToOrganization
{
    RHOrganizationBindVC *bindVC = [[RHOrganizationBindVC alloc]init];
    [self.navigationController pushViewController:bindVC animated:YES];
}

#pragma mark -------- network ------------

-(void)getCanUpdateDevice
{
    kWeakSelf;
    [BaseModel startGetWithCompletionAPIKey:H_getCanUpdateDevice argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            if (![[RHTools getCurrentVC] isKindOfClass:[RHOverviewVC class]]) return;
            if (request.responseJSONObject[@"data"]) {
                if (request.responseJSONObject[@"data"][@"deviceId"]) {
                    QMUIAlertController *alertView = [[QMUIAlertController alloc]initWithTitle:@"温馨提示".rh_localized message:@"有可升级的固件,是否升级?".rh_localized preferredStyle:QMUIAlertControllerStyleAlert];
                    QMUIAlertAction *cancel = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                        
                    }];
                    
                    QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"升级".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                        RHDeviceModel *devModel = [[RHDeviceModel alloc]init];
                        devModel.deviceId = request.responseJSONObject[@"data"][@"deviceId"];
                        RHFirmwareListVC *fireListVC = [[RHFirmwareListVC alloc]init];
                        fireListVC.deviceModel = devModel;
                        [[RHTools getCurrentVC].navigationController pushViewController:fireListVC animated:YES];
                    }];
                    [alertView addAction:sure];
                    [alertView addAction:cancel];
                    [alertView showWithAnimated:YES];
                }
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
    }];
}

//资产数据 收益数据 设备监控
-(void)getStationStatus
{
    [BaseModel startGetWithCompletionAPIKey:H_homeRunData argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        self.plantStatusDic = request.responseJSONObject[@"data"];
        
        NSInteger count = [self.plantStatusDic[@"fault"] integerValue] + [self.plantStatusDic[@"alarm"] integerValue];
        self.pointView.hidden = (count == 0);
        [self.tableView reloadData];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}
#pragma mark -------- 当日数据  发电 买电 卖电
-(void)getRunData
{
    [QMUITips showLoadingInView:self.view];
   
    [BaseModel startWithCompletionAPIKey:H_getRunData argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.runDic = request.responseJSONObject[@"data"];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}



//设备状态
-(void)getDeviceStatus
{
    [BaseModel startGetWithCompletionAPIKey:H_getDeviceStatus argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        self.deviceStatusArr = request.responseJSONObject[@"data"];
        [self.tableView reloadData];
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


#pragma mark ------ 能量统计(充电 放电)

-(void)getChargeAndDischargeWithChartModel:(DevChartModel*)chartModel
{
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    [BaseModel startGetWithCompletionAPIKey:H_getChargeDischarge argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            chartModel.allDataArray = request.responseJSONObject[@"data"][@"chart"];
            [self.tableView reloadData];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

//节能减排(社会贡献)
-(void)getEmissionReduction
{
    [BaseModel startGetWithCompletionAPIKey:H_getEmissionReduction argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        self.emissionReductionDic = request.responseJSONObject[@"data"];
        [self.tableView reloadData];
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


#pragma mark ---------- 获取电站列表 能量流向-----------
-(void)getPlantList
{
    //获取自己的电站列表
    NSDictionary *para = @{@"pageNum":@(1),
                           @"pageSize":@(1000)
    };
    [RHPlantModel startGetWithCompletionAPIKey:H_plantListByStatus argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSArray *arr = resultModel.data;
            // 按照电站在线优先，设备数量多的进行排序
            NSSortDescriptor *statusSort = [NSSortDescriptor sortDescriptorWithKey:@"status" ascending:YES];
            NSSortDescriptor *countSort = [NSSortDescriptor sortDescriptorWithKey:@"deviceAmount" ascending:NO];
            NSArray *sortDescriptors = @[statusSort, countSort];
            self.plantArr = [arr sortedArrayUsingDescriptors:sortDescriptors];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips hideAllToastInView:self.view animated:YES];
        [self.tableView endHeaderRefresh];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    UIView *headView = kView;
//  
//    UILabel *titleLab = [[QMUILabel alloc]init];
//    titleLab.font = kBOLDSYSTEMFONT(16);
//    titleLab.textColor = kColorRGB(0, 0, 0);
//    titleLab.textAlignment = NSTextAlignmentLeft;
//    titleLab.text = self.titleArr[section];
//    [headView addSubview:titleLab];
//    
//    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(headView).offset(15);
//        make.bottom.mas_offset(-10);
//     }];
    
   return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0)return 0.0;
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return  [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakSelf;
   
    if (indexPath.section == 0){//资产数据 收益数据  设备监控
        RHPlantStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHPlantStatusCell"];
        cell.dic = self.plantStatusDic;
        cell.runDic = self.runDic;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.plantAction = ^{
            RHMeAssetContainVC *plantVC = [[RHMeAssetContainVC alloc]init];
            plantVC.defaultTitle = @"电站".rh_localized;
            [weakSelf.navigationController pushViewController:plantVC animated:YES];
            
        };
        cell.deviceAction = ^{
            RHMeAssetContainVC *deviceVC  = [[RHMeAssetContainVC alloc]init];//电站,系统,设备
            deviceVC.defaultTitle = @"设备".rh_localized;
            [weakSelf.navigationController pushViewController:deviceVC animated:YES];
            
            
        };
        return cell;
    }else if (indexPath.section == 1){//能量统计
        RHEnergyStatisticsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PECumulativeGainCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        DevChartModel *chartModel = [self.chartParamsModel.chartList firstObject];
        cell.chartModel = chartModel;
        //选择参数
        cell.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index atIndexpath:indexPath];
        };
        
        cell.subTimeBlock = ^{//日期往前
            [weakSelf subTimeAction:indexPath];
        };
        
        cell.addTimeBlock = ^{//日期往后
            [weakSelf addTimeAction:indexPath];
        };
        
        cell.changeTimeBlock = ^{//选择日期
            [weakSelf changeDate:indexPath];
        };
        
        //全屏
        cell.fullChartBlock = ^{
            [weakSelf fullAction:indexPath.section];
        };
        
        cell.chartModel = [self.chartParamsModel.chartList firstObject];
        return cell;
    }else if (indexPath.section == 2){//节能减排(社会贡献)
        RHEnergySaveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHEnergySaveCell"];
        cell.dic = self.emissionReductionDic;
        return cell;
    }
 
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}



#pragma mark ----------------- Action --------------------
#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------
//工具选择项
- (void)selectTopTool:(NSInteger)index atIndexpath:(NSIndexPath *)indexpath{
    
    DevChartModel *chartModel ;
    
    chartModel = [self.chartParamsModel.chartList firstObject];
    
    
    if (index == 0) {//Day
        chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.dayParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
       
    }else if (index == 1) {//Month
        chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.monthParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 2) {//Year
        chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.yearParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 4) {//Total
        chartModel.timeType = TimeType_Total;
       
    }
    
    [self getChargeAndDischargeWithChartModel:chartModel];

}
#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
 
    chartModel = [self.chartParamsModel.chartList firstObject];
   
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYear;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSTimeInterval timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%ld",(NSInteger)timeSp];
        
       
        [self getChargeAndDischargeWithChartModel:chartModel];
       
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    datePickerV.maxLimitDate = [NSDate date];
    datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-10 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    
    [datePickerV show];
}
#pragma mark ------ 后一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
    
    chartModel = [self.chartParamsModel.chartList firstObject];
  
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%ld",(long)interval];
    
    
   
    [self getChargeAndDischargeWithChartModel:chartModel];
    
}

#pragma mark ------ 前一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
  
    chartModel = [self.chartParamsModel.chartList firstObject];
   
    
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    
    [self getChargeAndDischargeWithChartModel:chartModel];
   
}


- (void)fullAction:(NSInteger)index{
    DevChartModel *chartModel ;
   
    chartModel = [self.chartParamsModel.chartList firstObject];
    
    NSInteger type = 2;
    if (chartModel.monthParams.count>0) {
        type = 1;
    }
    if (chartModel.yearParams.count>0) {
        type = 0;
    }
    DevChartModel *model = [chartModel modelCopy];
    RHChargeFullChartVC *vc = [[RHChargeFullChartVC alloc] initWithModel:model toolType:type ];
    
    [self.navigationController pushViewController:vc animated:NO];
   
    
}


#pragma mark ----- 检查二维码信息 ----------
-(void)checkContent:(NSString *)content
{
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error= nil;
    NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (![dicInfo isKindOfClass:[NSDictionary class]]){
        [QMUITips showError:@"数据错误".rh_localized];
        return;
    }
    NSLog(@"---->扫描到的信息:%@",content);
    //没有组织id 则不能绑定
    if([dicInfo[@"brandId"] integerValue] == 0){
        [QMUITips showError:@"没有组织信息".rh_localized];
        return;
    }
    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_parsingInvitationCodes argument:@{@"invitationCode":dicInfo[@"QRCode"]} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
           
                kWeakSelf;
                QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@ %@ ?",@"绑定用户".rh_localized,request.responseJSONObject[@"data"][@"email"]] preferredStyle:QMUIAlertControllerStyleAlert];
                
                [alertVC addAction:[QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    [QMUITips showLoadingInView:weakSelf.view];
                    NSDictionary *para = @{@"sendEmail":request.responseJSONObject[@"data"][@"email"],
                                           @"userId":request.responseJSONObject[@"data"][@"userId"]};
                    [BaseModel startWithCompletionAPIKey:H_bindSuper argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                        if(resultModel.code == 200){
                            
                            [QMUITips showSucceed:@"绑定用户成功".rh_localized inView:self.view hideAfterDelay:1];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                //绑定成功后获取一下个人信息,根据角色重新加载对应控制器
                                [QMUITips showLoadingInView:weakSelf.view];
                                [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
                                    [[NSNotificationCenter defaultCenter]postNotificationName:UserRoleDidChangeNotification object:nil];
                                }];
                            });
                        }
                        
                        
                    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                                
                    }];
                    
                }]];
                [alertVC addAction:[QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleDefault handler:nil]];
                [alertVC showWithAnimated:YES];
           
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
 
   
}


#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
                    [weakSelf checkContent:content];
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }else{
        NSLog(@"摄像头不可用");
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
